package com.yhy.shiro.realm;

import java.sql.Connection;
import java.util.HashSet;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.yhy.shiro.dao.UserDao;
import com.yhy.shiro.entity.User;
import com.yhy.util.DbUtil;

public class MyRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		Connection connection = null;
		DbUtil dbUtil = new DbUtil();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		try {
			connection = dbUtil.getCon();
			UserDao userDao = new UserDao(connection);
			
			//设置角色
			HashSet<String> roleNames = new HashSet<String>();
			roleNames.add( userDao.getRoleName(userName) );
			authorizationInfo.setRoles( roleNames );	
			//设置权限
			Integer roleId = userDao.getUserByName(userName).getRoleId();
			authorizationInfo.setStringPermissions( userDao.getPerminssions(roleId));
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				dbUtil.closeCon(connection);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return authorizationInfo;
	}

	// 填充 SimpleAuthenticationInfo shiro 用来验证用户密码
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		Connection connection = null;
		DbUtil dbUtil = new DbUtil();

		try {
			connection = dbUtil.getCon();
			UserDao userDao = new UserDao(connection);
			User user = userDao.getUserByName(userName);

			if (null == user) {
				throw new UnknownAccountException();
			}

			SimpleAuthenticationInfo authenticationInfo = 
					new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(), getName());
			
			return authenticationInfo;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(connection);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
